package cn.iocoder.yudao.module.happycore.controller.admin.file;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.happycore.constants.DirectoryType;
import cn.iocoder.yudao.module.happycore.controller.admin.oxdirectory.vo.OxDirectorySaveReqVO;
import cn.iocoder.yudao.module.happycore.dal.dataobject.oxdirectory.OxDirectoryDO;
import cn.iocoder.yudao.module.happycore.dal.dataobject.oxproject.OxProjectDO;
import cn.iocoder.yudao.module.happycore.service.oxdirectory.OxDirectoryService;
import cn.iocoder.yudao.module.happycore.service.oxproject.OxProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.happycore.constants.ErrorCodeConstants.OX_DIRECTORY_NOT_EXISTS;

@RestController
public class FileUploadController {

    // 根上传目录（建议从配置文件读取）
//    private static final String BASE_UPLOAD_DIR = "uploads/";

    @Autowired
    public OxProjectService oxProjectService;
    @Autowired
    public OxDirectoryService oxDirectoryService;

    // 路径合法性校验：只允许字母、数字、下划线、中划线、斜杠，且不能以 / 开头或包含 ..
    private static final Pattern PATH_PATTERN = Pattern.compile("^[a-zA-Z0-9_\\-/]+$");

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFiles(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam("directoryId") Long directoryId) {

        OxDirectoryDO oxDirectory = oxDirectoryService.getOxDirectory(directoryId);
        if (ObjectUtils.isEmpty(oxDirectory)) {
            throw exception(OX_DIRECTORY_NOT_EXISTS);
        }
        OxProjectDO oxProject = oxProjectService.getOxProject(oxDirectory.getProjectId());
        String uploadPath = oxProject.getProjectPath()+ DirectoryType.getPath(oxDirectory.getType()) + "/" + oxDirectory.getDirectoryName();

        if (files == null || files.length == 0) {
            return ResponseEntity.badRequest().body("请至少上传一个文件");
        }



        Path targetDir = Paths.get(uploadPath).normalize();

        try {
            Files.createDirectories(targetDir);
        } catch (IOException e) {
            return ResponseEntity.status(500).body("无法创建目标目录");
        }

        // 允许的图片 MIME 类型
        List<String> allowedContentTypes = List.of(
                "image/jpeg",
                "image/png",
                "image/gif",
                "image/bmp",
                "image/webp"
        );

        // 允许的图片扩展名（可选，用于双重校验）
        List<String> allowedExtensions = List.of(".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp");

        List<String> uploadedFileNames = new ArrayList<>();
        for (MultipartFile file : files) {
            if (file.isEmpty()) continue;

            // 1. 检查 MIME 类型
            String contentType = file.getContentType();
            if (contentType == null || !allowedContentTypes.contains(contentType.toLowerCase())) {
                return ResponseEntity.badRequest()
                        .body("文件类型不支持: " + file.getOriginalFilename() + " (MIME: " + contentType + ")");
            }

            // 2. 检查文件扩展名（更安全）
            String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
            if (originalFilename.contains("..")) {
                return ResponseEntity.badRequest().body("文件名包含非法路径");
            }

            String extension = getFileExtension(originalFilename).toLowerCase();
            if (!allowedExtensions.contains(extension)) {
                return ResponseEntity.badRequest()
                        .body("文件扩展名不被允许: " + originalFilename);
            }

            try {
                Path filePath = targetDir.resolve(originalFilename);
                Files.copy(file.getInputStream(), filePath);
                uploadedFileNames.add(filePath.toString());
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.status(500).body("文件上传失败: " + file.getOriginalFilename());
            }
        }
        Integer imagesNum = oxDirectory.getImagesNum();
        Integer num = imagesNum+uploadedFileNames.size();
        oxDirectory.setImagesNum(num);
        OxDirectorySaveReqVO bean = BeanUtils.toBean(oxDirectory, OxDirectorySaveReqVO.class);
        oxDirectoryService.updateOxDirectory(bean);
        return ResponseEntity.ok("成功上传 " + uploadedFileNames.size() + " 个图片文件到: " + targetDir);
    }

    // 辅助方法：获取文件扩展名（带点）
    private String getFileExtension(String filename) {
        if (filename == null || filename.isEmpty()) {
            return "";
        }
        int lastDotIndex = filename.lastIndexOf(".");
        if (lastDotIndex >= 0) {
            return filename.substring(lastDotIndex);
        }
        return "";
    }

    private boolean isValidUploadPath(String path) {
        if (path == null || path.isEmpty() || path.startsWith("/") || path.contains("..")) {
            return false;
        }
        return PATH_PATTERN.matcher(path).matches();
    }
}